<template>
  <el-row>
    <div class="handle-box">
      <el-row>
        <classify-select v-model="query.classifyid" />
      </el-row>
      <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection" :disabled="query.recycle"
        >批量删除</el-button
      >
      <el-input v-model="query.qw" placeholder="关键词" class="handle-input mr10"></el-input>
      <el-button class="mr10" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-switch
        class="mr10"
        v-model="query.recycle"
        @input="getGoodsList"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="回收站"
      >
      </el-switch>
      <el-switch
        v-if="power.includes('goods.all')"
        class="mr10"
        v-model="query.all"
        @input="getGoodsList"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="所有店铺"
      >
      </el-switch>
      <el-button
        type="primary"
        icon="el-icon-plus"
        v-to="{ name: 'goods-editing', params: { id: 'new' }, query: { classifyid: query.classifyid } }"
      >
        新增
      </el-button>
    </div>
    <el-table
      :data="goods"
      border
      class="table"
      ref="multipleTable"
      header-cell-class-name="table-header"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" fixed="left"></el-table-column>
      <el-table-column prop="classify.name" label="所属分类" align="center"></el-table-column>
      <el-table-column label="单价">
        <template v-slot="{ row }">{{ row.price | price }}</template>
      </el-table-column>
      <el-table-column label="封面" align="center" width="80">
        <template v-slot="{ row }">
          <el-image class="table-td-thumb" :src="row.cover | imgurl" :preview-src-list="row.image | imgurl"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标签">
        <template v-slot="{ row }">
          <div class="tags-box-ellipsis" @click="openTags(row.tags, row.id)">
            <el-tag class="tag" v-for="tag in row.tags" :key="tag">{{ tag }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" align="center" width="100"></el-table-column>
      <el-table-column label="品牌">
        <template v-slot="{ row }">
          <span class="brand-text" @click="openBrand(row.brand, row.id)">
            <span v-if="row.brand">
              {{ row.brand.name }}
            </span>
            <el-tag v-else type="danger">品牌不存在</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="146" align="center">
        <template v-slot="{ row }">
          {{ row.createdAt | date }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="80">
        <template v-slot="{ row }">
          <el-tag :type="row.publish ? 'success' : 'danger'">{{ row.publish ? '已上架' : '未上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="210" fixed="right">
        <template v-slot="{ row }">
          <template v-if="query.recycle">
            <el-button type="text" icon="el-icon-refresh" @click="goodsRecycle(row)"> 恢 复 </el-button>
          </template>
          <template v-else>
            <el-button type="text" icon="el-icon-edit" v-to="{ name: 'goods-editing', params: { id: row.id } }"> 编 辑 </el-button>
            <el-button type="text" icon="el-icon-delete" class="danger" @click="handleDelete(row)"> 删 除 </el-button>
            <el-button
              v-if="row.publish"
              type="text"
              icon="el-icon-download"
              class="warning"
              @click="modifyGoods({ publish: 0, id: row.id }, '下架')"
            >
              下架
            </el-button>
            <el-button v-else type="text" icon="el-icon-upload2" class="success" @click="modifyGoods({ publish: 1, id: row.id }, '上架')">
              上架
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes, jumper"
        :current-page="query.page"
        :page-size="query.size"
        :page-sizes="pageSizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <el-dialog title="标签详情" :visible.sync="tags.showDialog" width="20%">
      <template>
        <tags v-model="tags.data" @input="inputTags" />
      </template>
      <template v-slot:footer>
        <el-button @click="modifyTags({ id: tags.id, tags: tags.data })" type="primary" v-if="tags.showModifyButton">保 存</el-button>
        <el-button @click="tags.showDialog = false">关 闭</el-button>
      </template>
    </el-dialog>
    <el-dialog title="品牌详情" :visible.sync="brand.showDialog" width="20%">
      <template>
        <div class="center-column">
          <h3>{{ brand.data.name }}</h3>
          <el-image :src="brand.data.logo | imgurl" />
        </div>
      </template>
      <template v-slot:footer>
        <el-button @click="brand.showDialog = false">关 闭</el-button>
      </template>
    </el-dialog>
  </el-row>
</template>

<script>
import ClassifySelect from '@/components/ClassifySelect.vue'
import Tags from '@/components/Tags.vue'

import { goodsMy, goodsDel, goodsDels, goodsModify, goodsRecycle } from '@/api/goods'
import { deepClone, analysisQuery } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  components: {
    ClassifySelect,
    Tags,
  },
  computed: {
    ...mapGetters('user', ['power']),
  },
  data() {
    return {
      query: {
        qw: '',
        classifyid: '',
        page: 1,
        size: 10,
        recycle: false,
        all: false,
      },
      tags: {
        showModifyButton: false,
        showDialog: false,
        data: [],
        id: 0,
      },
      brand: {
        showModifyButton: false,
        showDialog: false,
        data: {},
        id: 0,
      },
      loading: false,
      pageSizes: [5, 10, 30, 100],
      goods: [],
      multipleSelection: [],
      total: 0,
    }
  },
  watch: {
    query: {
      deep: true,
      handler(query) {
        this.$router.replace({ path: './', query }).catch((err) => err)
      },
    },
  },
  methods: {
    /**打开标签详情 */
    openTags(v, id) {
      if (this.query.recycle) return this.$message.warning('回收站中商品禁止编辑,请先恢复商品')
      this.tags.showDialog = true
      this.tags.data = deepClone(v)
      this.tags.id = id
    },
    /**打开品牌详情 */
    openBrand(v, id) {
      if (this.query.recycle) return this.$message.warning('回收站中商品禁止编辑,请先恢复商品')
      if (!v) return this.$message.warning('品牌不存在或已被移除')
      this.brand.showDialog = true
      this.brand.data = deepClone(v)
      this.brand.id = id
    },
    /**同步标签 */
    modifyTags(v) {
      this.modifyGoods(v, '修改标签')
      this.tags.showModifyButton = false
      this.tags.showDialog = false
    },
    /**输入标签 */
    inputTags() {
      this.tags.showModifyButton = true
    },
    /**修改商品 */
    async modifyGoods(v, s) {
      const data = await goodsModify(v)
      if (data.code !== 200) return this.$message.error(s + '失败,错误码:' + data.code)
      this.$message.success(s + '成功')
      this.getGoodsList()
    },
    /**获取商品列表 */
    async getGoodsList() {
      this.loading = true
      const data = await goodsMy(this.query)
      if (data.code !== 200) return this.$message.error('获取商品列表失败,点击搜索重新查询,错误码:' + data.code)
      this.loading = false
      this.total = data.total
      this.goods = data.data
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, 'page', 1)
      this.getGoodsList()
    },
    /**恢复 */
    async goodsRecycle(row) {
      const { code } = await goodsRecycle(row)
      if (code !== 200) return this.$message.error('恢复商品失败,错误码:' + code)
      this.$message.success('已恢复')
      this.getGoodsList()
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning',
      })
        .then(async () => {
          const { code } = await goodsDel(row)
          if (code !== 200) return this.$message.error('删除商品失败,错误码:' + code)
          this.$message.success('删除成功')
          this.getGoodsList()
        })
        .catch(() => {})
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**多选删除 */
    delAllSelection() {
      const { multipleSelection } = this
      if (!multipleSelection.length) return this.$message('请勾选要删除的商品')
      const ids = multipleSelection.map((e) => e.id)
      this.$confirm(`确定要删除所选的${multipleSelection.length}个商品吗？`, '提示', {
        type: 'warning',
      })
        .then(async () => {
          const { code } = await goodsDels({ ids })
          if (code !== 200) return this.$message.error('删除商品失败,错误码:' + code)
          this.$message.success('删除成功')
          this.getGoodsList()
        })
        .catch(() => {})
    },
    // 分页导航
    handlePageChange(val) {
      console.log(11)
      this.$set(this.query, 'page', val)
      this.getGoodsList()
    },
    handleSizeChange(v) {
      this.query.size = v
      this.getGoodsList()
    },
  },
  created() {
    Object.assign(this.query, analysisQuery(this.$route.query))
    this.handleSearch()
  },
}
</script>

<style lang="scss" scoped>
.brand-text {
  cursor: pointer;
}

.tags-box-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}

.tag {
  margin-right: 6px;
}

.handle-box {
  margin-bottom: 12px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.warning {
  color: #e6a23c;
}
.danger {
  color: #ff0000;
}
.success {
  color: #67c23a;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
